﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using NC.Cather;
using NC.Infrastructure.Cache;
using NC.Infrastructure.Data;
using NC.Infrastructure.DomainDto;
using ScrapySharp.Extensions;
using domainEntity = NC.Cather.ContentParams;

namespace NC.Service.ContentParams
{
    public class ContentParamsService:IContentParamsService
    {
        private readonly IRepository<domainEntity> _contentParamsRepository;

        public ContentParamsService(IRepository<domainEntity> contentParamsRepository)
        {
            this._contentParamsRepository = contentParamsRepository;
        }

        #region Method

        public void Insert(domainEntity entity)
        {
            _contentParamsRepository.Insert(entity);
        }

        public domainEntity Get(int id)
        {
            return _contentParamsRepository.Get(id);
        }

        public IQueryable<domainEntity> GetAll()
        {
            return _contentParamsRepository.Entities;
        }

        public IQueryable<domainEntity> Get(Expression<Func<domainEntity, bool>> filter)
        {
            return _contentParamsRepository.Get(filter);
        }

        public void Delete(domainEntity entity)
        {
            _contentParamsRepository.Delete(entity);
        }

        public void Update(domainEntity entity)
        {
            _contentParamsRepository.Update(entity);
        }

        public IQueryable<SimpleDto> SimpleDtos()
        {
            return _contentParamsRepository.Entities.Select(n => new SimpleDto()
            {
                Id = n.Id
            });
        }


        public domainEntity GetContent(domainEntity entity,string testUrl,HttpMethod method)
        {
            //获取第一个Container
            var node = CatherManager.GetNodes(testUrl, entity.ContainerSelector, method).FirstOrDefault();
            if (node == null)
                return null;
            //获取Title
            var temp = node.CssSelects(entity.TitleSelector).FirstOrDefault();
            entity.TitleSelector = temp == null ? "" : temp.InnerText;
            //获取Author
            temp = node.CssSelects(entity.AuthorSelector).FirstOrDefault();
            entity.AuthorSelector = temp == null ? "" : temp.InnerText;
            //获取发布时间
            temp = node.CssSelects(entity.ComeUpTimeSelector).FirstOrDefault();
            entity.ComeUpTimeSelector = temp == null ? "" : temp.InnerText;
            //获取文章类型
            temp = node.CssSelects(entity.TypeSelector).FirstOrDefault();
            entity.TypeSelector = temp == null ? "" : temp.InnerText;
            //获取文章详细内容
            temp = node.CssSelects(entity.ContentSelector).FirstOrDefault();
            entity.ContentSelector = temp == null ? "" : temp.InnerHtml;
            return entity;
        }

        public void Commit()
        {
            _contentParamsRepository.Commit();
        }

        #endregion
    }
}
